/**
 * <p>Title: OperaterParser.java</p>
 * <p>Description: 算子解析器</p>
 * <p>Copyright: Copyright (c) 2018</p>
 *
 * @author ji'anyuan
 * @date 2018年3月10日
 * @version 1.0
 */
package org.mango.jiayin.operater.operater;

import java.util.UUID;
import org.mango.jiayin.operater.constants.Constants.Mark;
import org.mango.jiayin.operater.domain.OperaterDo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * Title: OperaterParser
 * </p>
 * <p>
 * Description: 算子解析器
 * </p>
 *
 * @author ji'anyuan
 * @date 2018年3月10日
 */
public class OperaterParser {

  private static final Logger logger = LoggerFactory
      .getLogger(OperaterParser.class);

  /**
   * <p>
   * Title: parase
   * </p>
   * <p>
   * Description:解析算子
   * </p>
   *
   * @param opStr 例如:split(msg, |)
   */
  public static OperaterDo parase(String opStr) {
    OperaterDo opDo = null;
    if (opStr == null || "".equals(opStr)) {
      logger.error("opStr is empty");
      return null;
    }

    if (opStr.replace(Mark.EsleftPar, "").contains(Mark.leftPar)
        && opStr.replace(Mark.EsrightPar, "").contains(Mark.rightPar)
        && opStr.replace(Mark.EsleftPar, "").replace(Mark.EsrightPar, "").indexOf(Mark.leftPar) < opStr.replace(Mark.EsleftPar, "").replace(Mark.EsrightPar, "")
        .lastIndexOf(Mark.rightPar)) {
      int leftPar = opStr.indexOf(Mark.leftPar);
      int rightPar = opStr.lastIndexOf(Mark.rightPar);
      if (leftPar >= rightPar) {
        return null;
      }
      String opName = opStr.substring(0, leftPar);
      if (opName.contains(Mark.separate)) {
        opName = opName.substring(opName.lastIndexOf(Mark.separate) + Mark.separate.length());
      }

      opDo = new OperaterDo();

      opDo.setId("$" + opName
          + UUID.randomUUID().toString().replace("-", ""));

      opDo.setOpName(opName);

      opDo.setOpParames(opStr.substring(leftPar + 1, rightPar));

      opDo.setNestedOp(parase(opStr.substring(leftPar + 1, rightPar)));
    }

    return opDo;
  }
}
